package cube.orekaria.com;

import java.util.Random;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;

public class CubeActivity extends Activity implements View.OnClickListener {
	private static final int MARGIN = 0;
	private static final int MAX = 10;
	Hero _hero;
	Point _clientSize;
	Random _ran;
	Square[][] _board;

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// initialize some variables
		_hero = new Hero();
		_board = new Square[MAX][MAX];
		for (int x = 0; x < MAX; x++) {
			for (int y = 0; y < MAX; y++) {
				_board[x][y] = new Square();
			}
		}
		ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
		pb.setMax(15);
		TextView tv = (TextView) findViewById(R.id.textView1);
		// tv.setText("Hurry up!!. Find the exit!");

		_ran = new Random(Double.doubleToLongBits(Math.random()));

		// add the board
		TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);
		createBoard(tl);

		// create the traps
		Point p;
		for (int i = 0; i < 25; i++) {
			do {
				p = generateRandomPoint();
			} while (_board[p.x][p.y].isTrap);
			_board[p.x][p.y].isTrap = true;
		}

		// create the exit
		do {
			p = generateRandomPoint();
		} while (_board[p.x][p.y].isTrap);
		_board[p.x][p.y].isExit = true;

		// send the hero to do the things that heros do
		do {
			p = generateRandomPoint();
		} while (_board[p.x][p.y].isTrap || _board[p.x][p.y].isExit);
		_hero.Location = p;
		setAvailables(p);

		// paint changes
		updateLayout(tl);
	}

	/**
	 * Sets the squares that are available for movement
	 * 
	 * @param p
	 *            the point where our hero is located
	 */
	private void setAvailables(Point p) {
		for (int x = 0; x < MAX; x++) {
			for (int y = 0; y < MAX; y++) {
				_board[x][y].isAvailable = false;
			}
		}
		if (p.x > 0)
			_board[p.x - 1][p.y].isAvailable = true;
		if (p.y > 0)
			_board[p.x][p.y - 1].isAvailable = true;
		if (p.x < MAX - 1)
			_board[p.x + 1][p.y].isAvailable = true;
		if (p.y < MAX - 1)
			_board[p.x][p.y + 1].isAvailable = true;
	}

	/**
	 * Generates a random point in the board
	 * 
	 * @return a random point in the board
	 */
	private Point generateRandomPoint() {
		int x = _ran.nextInt(MAX);
		int y = _ran.nextInt(MAX);
		Point p = new Point(x, y);
		return p;
	}

	/**
	 * Creates the board layout
	 * 
	 * @param layout
	 */
	private void createBoard(TableLayout tl) {
		for (int x = 0; x < MAX; x++) {
			TableRow tr = new TableRow(this);
			for (int y = 0; y < MAX; y++) {
				Button b = new Button(this);
				b.setId(100 + x * 10 + y);
				b.setPadding(0, 0, 0, 0);
				b.setTextSize(8.0f);
				// b.setTextColor(Color.GRAY);
				b.setOnClickListener(this);
				b.setDrawingCacheEnabled(false);
				tr.addView(b, getBoardMaxSide() / MAX, getBoardMaxSide() / MAX);
			}
			tl.addView(tr);
		}
	}

	/**
	 * Fires when a square is clicked
	 */
	public void onClick(View view) {
		TextView tv = (TextView) findViewById(R.id.textView1);
		try {
			Button clickedButton = (Button) view;
			TableLayout tl = (TableLayout) (view.getParent().getParent());

			String s = String.format("%d", clickedButton.getId());
			// tv.setText(s);

			int x = Integer.parseInt(s.substring(1, 2));
			int y = Integer.parseInt(s.substring(2, 3));
			Square sq = _board[x][y];
			sq.isDiscovered = true;
			Point p = new Point(x, y);
			_hero.Location = p;
			setAvailables(p);
			if (sq.isTrap) {
				_hero.damageReceived();
				if (_hero.isDead()) {
					tv.setText("The hero has died :(");
				}
			} else if (sq.isExit) {
				_hero.IsExitFound = true;
				tv.setText("The hero has found the exit!!!");
			}

			updateLayout(tl);
		} catch (Exception ex) {
			tv.setText(ex.getMessage());
		}

	}

	/**
	 * Updates the layout of the board
	 * 
	 * @param tl
	 */
	private void updateLayout(TableLayout tl) {
		ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
		pb.setProgress(_hero.getLifePoints());

		for (int x = 0; x < tl.getChildCount(); x++) {
			TableRow tr = (TableRow) (tl.getChildAt(x));
			for (int y = 0; y < tr.getChildCount(); y++) {
				Button b = (Button) (tr.getChildAt(y));

				// color
				int c = Color.GRAY;

				if (_board[x][y].isDiscovered)
					if (_board[x][y].isTrap)
						c = Color.RED;
					else
						c = Color.LTGRAY;
				if (_hero.Location.x == x && _hero.Location.y == y)
					c = Color.BLUE;
				// if (_board[x][y].isTrap)
				// c = Color.RED;
				// if (_board[x][y].isAvailable)
				// c = Color.GREEN;

				// enabled
				if (_hero.isDead() || _hero.IsExitFound) {
					b.setEnabled(false);
					if (_board[x][y].isExit)
						c = Color.GREEN;
				} else if (b.isEnabled() != _board[x][y].isAvailable)
					b.setEnabled(_board[x][y].isAvailable);

				b.setBackgroundColor(c);
			}
		}
	}

	/**
	 * Gets the screen size of the Android device
	 * 
	 * @return The size of the screen
	 */
	private Point getClientSize() {
		if (_clientSize == null) {
			Display display = getWindowManager().getDefaultDisplay();
			_clientSize = new Point(display.getWidth(), display.getHeight());
			TextView tv = (TextView) findViewById(R.id.textView1);
			tv.setText(_clientSize.toString());
		}
		return _clientSize;
	}

	/**
	 * Gets the maximum side length of the board
	 * 
	 * @return The maximum side length
	 */
	private int getBoardMaxSide() {
		Point clientSize = getClientSize();
		if (clientSize.x < clientSize.y)
			return clientSize.x - 2 * MARGIN;
		else
			return clientSize.y - 2 * MARGIN;
	}
}
